﻿using System.Web.UI;

namespace Folks.UI
{
	public class FolksPageStatePersister : PageStatePersister
	{
		internal string PageStateKey;

        public FolksPageStatePersister(Page page)
            : base(page)
        {
            PageStateKey = "__FOLKSPAGESTATE" +
                Page.Request.AppRelativeCurrentExecutionFilePath;
        }

		public override void Load()
		{
			if (Page.Session[PageStateKey] != null)
			{
				string state = Page.Session[PageStateKey].ToString();
				Pair pair = (Pair)base.StateFormatter.Deserialize(state);
				base.ViewState = pair.First;
				base.ControlState = pair.Second;
			}
		}

		public override void Save()
		{
			if (base.ViewState != null || base.ControlState != null)
			{
				Pair pair = new Pair(base.ViewState, base.ControlState);
				string state = base.StateFormatter.Serialize(pair); 
				if (Page.Session[PageStateKey] == null)
					Page.Session.Add(PageStateKey, state);
				else
					Page.Session[PageStateKey] = state;
			}
		}
	}
}
